//
//  ST_PeculiarityVideoPlayView.swift
//  btvideo
//
//  Created by mac on 2020/2/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import KTVHTTPCache

class ST_PeculiarityVideoPlayView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let y = 1.cgFloat
        
        self.addSubview(play_image_view)
        play_image_view.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(38*y)
            make.height.equalTo(44*y)
        }
        
        self.addSubview(btn)
        btn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - Properties
    fileprivate lazy var play_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("IndexItem_icon_音乐播放")!)
        control.isHidden = true
//        control.contentMode = .center
        return control
    }()
    
    
    fileprivate lazy var btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.addTarget(self, action: #selector(play_view_handle), for: UIControl.Event.touchUpInside)
        return control
        
    }()
    
    fileprivate var player:AVPlayer?
    
    var alwaysHiddenPlaySign = false
    
    var isMuted = false
    
    /// 循环播放
    var loopPlay = false
    
    fileprivate var playing = false{
        didSet{
            
            if alwaysHiddenPlaySign == false{
                self.play_image_view.isHidden = playing
            }
            
        }
    }

    fileprivate var time_observer:Any?
    
    fileprivate var playerItem:AVPlayerItem?

//    fileprivate var playerLayer:AVPlayerLayer?
    
    fileprivate var avPlayerView:ST_PairsAVPlayerView?
    
//    MARK: - Private Method
    @objc func play_view_handle(){
        
        if !playing{
            self.continuePlay()
        }else{
            self.pause()
        }
    }
    
    //MARK: - Public Method
    
    var playSecondsClosure:((CGFloat)->())?
    
    func play(url:URL,gravity:AVLayerVideoGravity = .resizeAspectFill){
        
        
        guard let pUrl = KTVHTTPCache.proxyURL(withOriginalURL: url) else{
           print("缓存方案 创建代理Url失败：\(url)")
           return
        }
        
        let playerItem = AVPlayerItem(url: pUrl)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = self.isMuted
        self.player?.rate = 1.0//播放速度 播放前设置
        
        
        //进度条
        let mainQueue = DispatchQueue.main
        
        // Invoke callback every second
        let interval = CMTime(seconds:1.0/20.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        
        self.time_observer = self.player?.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue, using: {[weak self] (time) in
                    
            let seconds = CMTimeGetSeconds(time)

//            print("bug 12333-",seconds,"---who:",url)
            
            self?.playSecondsClosure?(seconds.cgFloat)
            
        })
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
        //创建显示视频的图层
        avPlayerView = ST_PairsAVPlayerView()
//        self.addSubview(avPlayerView!)
        
        self.insertSubview(avPlayerView!, belowSubview: play_image_view)
        
//        avPlayerView?.backgroundColor = UIColor.red
        
        avPlayerView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
        
        guard let castedLayer = avPlayerView?.layer as? AVPlayerLayer else{
            return
        }
        
        castedLayer.player = self.player
        castedLayer.videoGravity = gravity
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
    }
    
    func pause(){
        
        guard let player = self.player else { return  }
        
        player.pause()
        
        playing = false
    }
    
    func continuePlay(){
        
        if let player = self.player{
            player.play()
        }
        playing = true
    }
    
    func replay(){
        
        
        if let player = self.player{
            player.seek(to: CMTime.zero)
            player.play()
            playing = true
        }
    }
    
    func stop(){
            
        playing = false
        
        guard let player = self.player else { return  }
        
        
        if let ob = self.time_observer{
            player.removeTimeObserver(ob)
        }
        
        
        avPlayerView?.removeFromSuperview()
        avPlayerView = nil
        
        player.pause()
      
        NotificationCenter.default.removeObserver(self)
        
        self.player = nil
    }
    
    var playDidFinishClosure:(()->())?
    
    @objc func player_did_finish_playing(note: Notification) {
    
        if let playerItem = note.object as? AVPlayerItem {
            
            if loopPlay {
                
                playerItem.seek(to: CMTime.zero, completionHandler: nil)
                
                self.player?.play()
                
            }else if let currentItem = self.player?.currentItem,playerItem == currentItem{
                
//                print("DTPlayerViewController -- 两个Player 相同")
                    playDidFinishClosure?()
                
                return
            }
        }
    }
    
}
